package com.shutuo.callnumqixintian.screeninfo;

import com.instwall.callbase.tool.LogUtil;
import com.instwall.data.ScreenFetchState;
import com.instwall.screen.ScreenClient;
import com.shutuo.callnumqixintian.QixintianManager;
import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;




public class ScreenManager {

    private static ScreenManager sSelf;
    private  QXTianInfo mQXTianInfo;
    private ScreenListener screenListener;
    private com.instwall.screen.ScreenListener listener;
    private final ScreenClient mScreenClient = ScreenClient.get();

    private ScreenManager() {
        listener = new com.instwall.screen.ScreenListener() {
            @Override
            public void onScreenInfoChanged(@NotNull com.instwall.data.ScreenInfo screenInfo,
                                            @NotNull String s) {
                fetchScreenInfoTask(s);

            }

            @Override
            public void onScreenFetchStateChanged(@NotNull ScreenFetchState screenFetchState) {
            }
        };
    }
//    private ModifyList<ScreenListener> mScreenListeners = new ModifyList<>();

    public interface ScreenListener {
        void onScreenInfoChanged(QXTianInfo info);
    }



    public static ScreenManager get() {
        if (sSelf != null) return sSelf;
        synchronized (ScreenManager.class) {
            if (sSelf == null) sSelf = new ScreenManager();
        }
        return sSelf;
    }

    public void init(){
        mScreenClient.addListener(listener);

    }

    public void setScreenListener(ScreenListener screenListener){
        this.screenListener = screenListener;
    }

    public QXTianInfo getQxTianInfo() {

        return mQXTianInfo;
    }

    private void setQXTianInfo(QXTianInfo qxTianInfo){
        this.mQXTianInfo = qxTianInfo;
    }





    private void fetchScreenInfoTask(String string){

        JSONObject json = null;
        QXTianInfo qxTianInfo = null;
        try {
            json = new JSONObject(string);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            qxTianInfo = ScreenInfoParser.parseResult(json);
        } catch (Throwable throwable){
            throwable.printStackTrace();
        }
        setQXTianInfo(qxTianInfo);
        if(qxTianInfo!=null){
            screenListener.onScreenInfoChanged(qxTianInfo);
            LogUtil.LogI(null,QixintianManager.TAG+"[fetchScreenInfoTask] "+qxTianInfo.toString());
        }else {
            LogUtil.LogI(null,QixintianManager.TAG+"[fetchScreenInfoTask] qxTianInfo is null ");
        }
    }


}
